package com.wzh.musichome.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @文件描述
 * @作者 alexhigger
 * @创作日期 2020/11/29 22:24
 */
@Component
@ConfigurationProperties(prefix = "wzh.jw.config")
@Data
public class JwtUtil {

    private String secretKey;

    private long expires = 60*60*24*3;

    public String createJWT(String id,String subject,Boolean isLogin){
        long currentTimeMillis = System.currentTimeMillis();
        Date now = new Date(currentTimeMillis);
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256,secretKey)
                .claim("isLogin",isLogin);
        if (expires > 0){
            builder.setExpiration(new Date(currentTimeMillis+expires*1000));
        }
        return builder.compact();
    }

    public Claims paresJWT(String jwtToken){
        return  Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken).getBody();
    }
}
